// pages/order/order.js

import { Cart } from '../cart/cart-model.js';
import { Order } from '../order/order-model.js';
import { Address } from '../../utils/address.js';

var cart = new Cart();
var order = new Order();
var address = new Address();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null, //订单id号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var from = options.from;
    if(from == 'cart'){
      this._fromCart(options.account);
    }else{
      this._fromOrder(options.id);
    }
  },

    onShow: function () {
    if(this.data.id){
      this._fromOrder(this.data.id);
    }
  },

  //处理从购物车传递过来的数据
  _fromCart:function(account){
    var productsArr;
    this.data.account = account;

    productsArr = cart.getCartDateFromLocal(true);

    this.setData({
      productsArr: productsArr, //订单商品数据
      account: account, //订单商品总金额
      orderStatus: 0
    })

    //从服务器获取用户地址并做数据绑定
    address.getAddress((res) => {
      this._bindAddressInfo(res);
    });
  },

  //处理从‘我的订单’ 进来的数据
  _fromOrder:function(id){
    //如果订单已经生成则向服务器获取订单信息并展示
    if (id) {
      var that = this;
      order.getOrderInfoById(id, (data) => {
        that.setData({
          orderStatus: data.status,
          productsArr: data.snap_items,
          account: data.total_price,
          basicInfo: {
            orderTime: data.create_time,
            orderNo: data.order_no
          }
        });
        //订单快照的地址
        var addressInfo = data.snap_address;
        addressInfo.totalDetail = address.setAddressInfo(addressInfo);
        that._bindAddressInfo(addressInfo);
      });
    }
  },

  //编辑地址
  editAddress: function (event) {
    var that = this;

    wx.chooseAddress({
      success: function (res) {
        var addressInfo = {
          name: res.userName,
          moble: res.telNumber,
          totalDetail: address.setAddressInfo(res)
        }

        that._bindAddressInfo(addressInfo);

        //把地址保存到服务端
        address.submitAddress(res, (flag) => {
          if (!flag) {
            that.showTips('操作提示', '地址信息更新失败！');
          }
        })
      }
    })
  },

  /*
    提示窗口
    @params
    title - {string}提示标题
    content - {string}提示内容
    flag - {bool}是否跳转到 “我的页面”
   */
  showTips(title, content, flag) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (flag) {
          wx.switchTab({
            url: '/pages/my/my',
          })
        }
      }
    })
  },

  //绑定地址信息
  _bindAddressInfo: function (addressInfo) {
    this.setData({
      addressInfo: addressInfo
    })
  },

  //下单和付款
  pay: function () {
    if (!this.data.addressInfo) {
      this.showTips('下单提示', '请填写您的收货地址');
    }
    if (this.data.orderStatus == 0) {
      //向服务器发送请求-生成预订单-付款
      this._firstTimePay();
    } else {
      // this._oneMoresTimePay();
    }
  },

  //第一次支付
  _firstTimePay() {
    var orderInfo = [],
      productInfo = this.data.productsArr,
      order = new Order();

    //拿到订单信息
    for (let i = 0; i < productInfo.length; i++) {
      orderInfo.push({
        product_id: productInfo[i].id,
        count: productInfo[i].counts
      })
    }

    var that = this;
    //下订单  支付分两步，下订单生成订单，然后根据订单id来支付
    order.doOrder(orderInfo, (data) => {
      //如果订单生成成功
      if (data.pass) {
        var id = data.order_id;
        that.data.id = id;
        // that.data.fromCartFlag = false;

        //开始支付
        that._execPay(id);
      } else {
        //下单失败
        that._orderFail(data);
      }
    })
  },

  //开始支付，调用支付接口
  _execPay(id) {
    var that = this;
    order.execPay(id, (statusCode) => {
      if (statusCode != 0) {
        //将已购买的商品从用户购物车中删除
        that.deleteProducts();
        var flag = statusCode == 2;
        wx.navigateTo({
          url: '../pay-result/pay-result?id=' + id + '&flag=' + flag + '&from=order',
        })
      }
      
    })
  },

  /*
      *下单失败
      * params:
      * data - {obj} 订单结果信息
      * */
  _orderFail: function (data) {
    var nameArr = [],
      name = '',
      str = '',
      pArr = data.pStatusArray;
    for (let i = 0; i < pArr.length; i++) {
      if (!pArr[i].haveStock) {
        name = pArr[i].name;
        if (name.length > 15) {
          name = name.substr(0, 12) + '...';
        }
        nameArr.push(name);
        if (nameArr.length >= 2) {
          break;
        }
      }
    }
    str += nameArr.join('、');
    if (nameArr.length > 2) {
      str += ' 等';
    }
    str += ' 缺货';
    wx.showModal({
      title: '下单失败',
      content: str,
      showCancel: false,
      success: function (res) {
      }
    });
  },

  //将已购买的商品从用户购物车中删除
  deleteProducts: function () {
    var ids = [],
      arr = this.data.productsArr;
    for (let i = 0; i < arr.length; i++) {
      ids.push(arr[i].id);
    }
    cart.delete(ids);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})